package com.cnc.beanutils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.cnc.bas.db.JdbcDao;
import com.cnc.bas.util.SpringBeanFactory;
import com.cnc.ssm.UserInfo;
/**
 * 
 * @author 刘伟
 * @date   2008-1-10
 * @version 1.0
 */
public class UserFilter implements Filter {
	protected FilterConfig filterConfig = null;
	protected String actionname = null;
	private static JdbcDao dao = (JdbcDao)SpringBeanFactory.getBean(JdbcDao.BEAN_ID);
	public void destroy() {		
		filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {		 
			 HttpServletRequest httprequest = (HttpServletRequest)request;
			 String servletpath = httprequest.getServletPath();			 	
				HttpSession session = httprequest.getSession();
				String username = ((UserInfo)session.getAttribute(com.cnc.bas.util.Constants.USER_KEY)).getUserCode();				
				if(!servletpath.startsWith(this.actionname)){
						if(UserFilter.getUserType(username).equals("1")||UserFilter.judgeUser(username)){
							httprequest.getRequestDispatcher("/cdn/customermanager.do").forward(request, response);
						}else{
							chain.doFilter(request, response);
						}
					
				}else{
					chain.doFilter(request, response);
				}
				
				
				
				
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.actionname = filterConfig.getInitParameter("actionname");	

	}
	/**
	 * 通过用户登陆帐号 获得用户类型 如admin->1
	 * @param username
	 * @return
	 */
	public static String getUserType(String username){
		
		String sql = "select OPER_TYPE from PW_OPER where OPER_CODE=?";		
		List<String> params=new ArrayList<String>();
		params.add(username);
		Map map = dao.queryForMap(sql,params.toArray());		
		if(map==null) return "";
		return (String)map.get("OPER_TYPE");
	} 
	
	public static boolean judgeUser(String username){
		boolean flag = UserFilter.getUserType(username).equals("4");
		String sql = "select DISTINCT LoginOper from CS_NewOper";
		List list = dao.queryForList(sql);
		List cols = new ArrayList();
		for(Iterator it = list.iterator();it.hasNext();){
			Map map = (Map)it.next();
			cols.add(map.get("LoginOper"));
		}
		if(cols.contains(username)&&flag){
			return true;
		}
		return false;
	}
	
}
